#!/bin/sh

if [[ ! $window_number ]]; then
    window_number=0
fi

log_level=2
## 输出log
#   $1:     Log level. 1:DBG, 2:INF, 3:WAR, 4:ERR
#   $2:     Log message
log_printer() {
    lvl="???"
    if [[ "$1" -eq 1 ]]; then
        lvl="DBG"
    elif [[ "$1" -eq 2 ]]; then
        lvl="INF"
    elif [[ "$1" -eq 3 ]]; then
        lvl="WAR"
    elif [[ "$1" -eq 4 ]]; then
        lvl="ERR"
    else
        echo -e "Unknown log level: $1"
        exit 1
    fi
    if [[ $1 -ge $log_level ]]; then
        echo -e "`date +"%y%m%d_%H%M%S"`|$lvl  $2"
    fi
}
log_debug() {
    log_printer 1 "|$1"
}
log_title() {
    log_printer 2 "## $1"
}
log_info() {
    log_printer 2 "  $1"
}
log_error() {
    log_printer 4 "[x]$1"
}

## 创建窗口
#   $1:     window name
create_window() {
    win_num=$window_number
    log_title "Create window: $win_num:$1"
    $T new-window -t $win_num -n "$1"
    ((window_number++))
}

## 分割窗格
#   $1:     Src pane. <0:使用当前窗格
#   $2:     '|'=水平分割, '-'=垂直分割, '0'=不分割
#   $3:     执行命令. 有分割在新窗格, 无分割在原窗格
#   $4:     Src pane size. <=0:不设置
#   $5:     Dst pane size. <=0:不设置
split_pane() {
    str=""
    if [[ "$1" -ge 0 ]]; then
        str+="在pane $1"
        $T select-pane -t $1
    else
        str+="当前pane"
    fi
    nosplit=0
    direction=x
    cmd="$T split-window "
    if [[ "$2" == "0" ]]; then
        nosplit=1
    elif [[ "$2" == "|" ]]; then
        str+="左右分割"
        cmd+="-h"
    elif [[ "$2" == "-" ]]; then
        str+="上下分割"
        cmd+="-v"
        direction=y
    else
        log_error "Invalid param 2 in function: split_pane"
        exit 1
    fi
    if [[ $nosplit -eq 0 ]]; then
        log_debug "分割指令: $cmd"
        $cmd
    fi
    if [[ -n "$3" ]]; then
        str+=", 执行命令:$3"
        eval $T send-keys $3
    fi
    cmd="$T resize-pane -t "
    if [[ "$4" ]] && [[ "$4" -gt 0 ]]; then
        if [[ "$1" -lt 0 ]]; then
            log_error "没有指定原窗格"
            return
        fi
        str+=", 设原pane大小为$4"
        $cmd $1 -$direction $4
    fi
    if [[ $nosplit -eq 0 ]] && [[ "$5" ]] && [[ "$5" -gt 0 ]]; then
        str+=", 设新pane大小为$5"
        $cmd $(($1+1)) -$direction $5
    fi
    log_info "$str"
}

## 创建工程开发window
#   $1:     window name
#   $2:     project path
create_window_dev() {
    create_window $1
    split_pane 0 "|" "'cd $2' Enter 'nvim *.vimproject'" 100
    split_pane 0 0 "'cd $2' Enter 'git status' Enter"
    split_pane 0 "-" "'cd $2' Enter"
}

## 创建工程测试window
create_window_test() {
    create_window $1
    split_pane 0 0 "'cd $2' Enter"
    split_pane 0 "|" "'cd $2' Enter"
}

